package linkedlist.basic;

import linkedlist.ListNode;

/**
 * @Classname : ReverseLinkedList
 * @Description :
 * <a href="https://leetcode.cn/problems/reverse-linked-list/">206. 反转链表</a>
 * @Author : chentianyu
 * @Date 2022/12/22 00:51
 */


public class ReverseLinkedList {
    /**
     * 循环法
     *
     * @param head
     * @return
     */
    public ListNode reverseList2(ListNode head) {
        ListNode next = head, pre = null;
        while (next != null) {
            ListNode cur = next;
            next = next.next;
            cur.next = pre;
            pre = cur;
        }
        return pre;
    }

    /**
     * 递归法
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        return reverse(head, null);
    }

    private ListNode reverse(ListNode cur, ListNode pre) {
        if (cur == null) return pre;

        ListNode next = cur.next;
        cur.next = pre;
        return reverse(next, cur);
    }

}
